package com.tedu.springboot2206.controller;

import com.tedu.springboot2206.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {
    //表示保存所有用户信息的目录users
    private static File userDir;
    static {
        userDir=new File("./users");
        if(!userDir.exists()){
            userDir.mkdirs();
        }
    }



    @RequestMapping("/deleteUser")
    public void deleteUser(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理删除用户");
        String username=request.getParameter("username");
        System.out.println("要删除的用户是"+username);
        File file=new File(userDir,username+".obj");
        file.delete();
        System.out.println("已删除用户"+username);
        try {
            response.sendRedirect("/userList");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




@RequestMapping("/userList")
    public void userList(HttpServletRequest request,HttpServletResponse response){
    System.out.println("开始打开用户列表");
     List<User> userList=new ArrayList<>();
    File[] subs= userDir.listFiles(f->f.getName().endsWith(".obj"));
    for (File file:subs){
        try (FileInputStream fis=new FileInputStream(file);
             ObjectInputStream ois=new ObjectInputStream(fis);)
        {
            User user=(User)ois.readObject();
            userList.add(user);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    System.out.println(userList);

    try {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter pw= response.getWriter();
        pw.println("<!DOCTYPE html>");
        pw.println("<html lang=\"en\">");
        pw.println("<head>");
        pw.println("<meta charset=\"UTF-8\">");
        pw.println("<title>NorthDream</title>");
        pw.println("</head>");
        pw.println("<body>");
        pw.println("<center>");
        pw.println("<h1 class=\"hh\">用户列表</h1>");
        pw.println(" <table border=\"5px\">");
        pw.println("<tr>");
        pw.println("<td>用户名</td>");
        pw.println("<td>密码</td>");
        pw.println("<td>昵称</td>");
        pw.println("<td>年龄</td>");
        pw.println("<td>操作</td>");
        pw.println("</tr>");

for (User user:userList) {
    pw.println("<tr>");
    pw.println("<td>"+user.getName()+"</td>");
    pw.println("<td>"+user.getPassword()+"</td>");
    pw.println("<td>"+user.getName()+"</td>");
    pw.println("<td>"+user.getAge()+"</td>");
    pw.println("<td><a href='/deleteUser?username="+user.getUsername()+"'>删除</a></td>");
    pw.println("</tr>");
}

        pw.println("</center>");
        pw.println("</body>");
        pw.println("</html>");

    } catch (IOException e) {
        e.printStackTrace();
    }

}


    @RequestMapping("/loginUser")
 public void login(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理登录");

        //1获取参数
String username=request.getParameter("username");
String password=request.getParameter("password");
if(username==null||username.isEmpty()||password==null||password.isEmpty()){
    try {
        response.sendRedirect("/login_info_error.html");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return;
}
//处理登录
        //根据登录的用户名去user目录下寻找用户信息
        File file=new File(userDir,username+".obj");
      if(file.exists()){
          try(              FileInputStream fis=new FileInputStream(file);
                            ObjectInputStream ois=new ObjectInputStream(fis);) {
                       User user=(User)ois.readObject();
                       if(user.getPassword().equals(password)){
                           response.sendRedirect("/login_success.html");
                           return;
                       }
          } catch (IOException | ClassNotFoundException e) {
              e.printStackTrace();
          }
      }
        try {
            response.sendRedirect("/login_fail.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/regUser")
public void register(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理注册");
        /**
         *
         */
        //1获取注册页面上的表单信息
       String username=request.getParameter("username");
       String password=request.getParameter("password");
        String name=request.getParameter("name");
        String agestr=request.getParameter("age");
        System.out.println(username+password+name+agestr);
if(username==null||username.isEmpty()||password==null
||password.isEmpty()||name==null||name.isEmpty()||agestr==null||agestr.isEmpty()||
!agestr.matches("[0-9]+")){
    try {
        response.sendRedirect("./reg_info_error.html");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return;
}


        /**
         * 2
         * 将该用户信息序列化到文件中 User
         */
          int age=Integer.parseInt(agestr);//将年龄转换为Int值
        User user=new User(username,password,name,age);

        File file=new File(userDir,username+".obj");
         //如果该文件存在这说明这是一个重复的用户
        if(file.exists()){
            try {
                response.sendRedirect("/have_user.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        return;
        }

        try(FileOutputStream fos=new FileOutputStream(file);
            ObjectOutputStream oos=new ObjectOutputStream(fos);)
        {
            oos.writeObject(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
//3,
        try {
            response.sendRedirect("/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
